package cc.uncarbon.module.appapi.service;

import cc.uncarbon.framework.core.exception.BusinessException;
import cc.uncarbon.module.appapi.mapper.OrdersMapper;
import cc.uncarbon.module.appapi.mapper.PaymentMapper;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wechat.pay.java.service.partnerpayments.jsapi.model.Transaction;
import com.yanrumiao.entity.OrdersEntity;
import com.yanrumiao.entity.PaymentEntity;
import com.yanrumiao.enumns.OrdersStatusEnum;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.Date;

@RequiredArgsConstructor
@Service
@Slf4j
public class PaymentService {
    private final PaymentMapper paymentMapper;



    public PaymentEntity createPayment(OrdersEntity orders, int type) {
        PaymentEntity paymentEntity1 = paymentMapper.selectOne(new LambdaQueryWrapper<PaymentEntity>().eq(PaymentEntity::getOrderNo, orders.getOrderNo()));
        if (paymentEntity1 != null) {
            return paymentEntity1;
        }
        PaymentEntity paymentEntity = new PaymentEntity();
        try {

            paymentEntity.setAmount(orders.getPayMoney());
            paymentEntity.setContent(orders.getItemName());
            paymentEntity.setStatus(type);
            paymentEntity.setOrderNo(orders.getOrderNo());
            paymentEntity.setPayWay(1);
            paymentEntity.setUserId(orders.getUserId());

            paymentMapper.insert(paymentEntity);
            return paymentEntity;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }



    public PaymentEntity getPaymentByOrderNo(String orderNo) {
        LambdaQueryWrapper<PaymentEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper. eq(PaymentEntity::getOrderNo, orderNo);
        PaymentEntity paymentEntity = paymentMapper.selectOne(wrapper);
        if (orderNo == null || paymentEntity == null) {
            throw new BusinessException(500, "记录异常");
        }
        log.info("---------修改状态----paymentEntity"+paymentEntity);
        return paymentEntity;
    }

    public void updatePaymentStatusByOrderNo(String orderNo, int type) {
        log.info("---------修改状态----Payment");
        PaymentEntity payment = getPaymentByOrderNo(orderNo);
        log.info("---------修改状态----Payment"+payment);
        if (payment == null) {
            throw new BusinessException(500, "记录异常");
        }
        payment.setStatus(type);
        paymentMapper.updateById(payment);
    }
}
